package com.library.manager.dao;

import com.library.manager.model.Manager;
import com.library.util.JdbcUtil;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public class ManagerDaoImpl implements ManagerDao {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Manager findByUsernameAndPassword(String username, String password) {
        String sql = "SELECT * FROM manager WHERE managerusername = ? AND managerpassword = ?";
        List<Map<String, Object>> result = JdbcUtil.jdbcBySelect(sql, username, password);
        if (result != null && !result.isEmpty()) {
            return mapToManager(result.get(0));
        }
        return null;
    }

    @Override
    public Manager findByUsername(String username) {
        String sql = "SELECT * FROM manager WHERE managerusername = ?";
        List<Map<String, Object>> result = JdbcUtil.jdbcBySelect(sql, username);
        if (result != null && !result.isEmpty()) {
            return mapToManager(result.get(0));
        }
        return null;
    }

    @Override
    public int addManager(Manager manager) {
        String sql = "INSERT INTO manager (managerusername, managerpassword, managerfullname, createtime) VALUES (?, ?, ?, ?)";
        return JdbcUtil.jdbcByUpdate(sql,
                manager.getManagerusername(),
                manager.getManagerpassword(),
                manager.getManagerfullname(),
                manager.getCreatetime() != null ? sdf.format(manager.getCreatetime()) : null);
    }

    @Override
    public int updateManager(Manager manager) {
        String sql = "UPDATE manager SET managerusername = ?, managerpassword = ?, managerfullname = ? WHERE managerid = ?";
        return JdbcUtil.jdbcByUpdate(sql,
                manager.getManagerusername(),
                manager.getManagerpassword(),
                manager.getManagerfullname(),
                manager.getManagerid());
    }

    @Override
    public int deleteManager(Integer managerid) {
        String sql = "DELETE FROM manager WHERE managerid = ?";
        return JdbcUtil.jdbcByUpdate(sql, managerid);
    }

    private Manager mapToManager(Map<String, Object> map) {
        Manager manager = new Manager();
        manager.setManagerid((Integer) map.get("managerid"));
        manager.setManagerusername((String) map.get("managerusername"));
        manager.setManagerpassword((String) map.get("managerpassword"));
        manager.setManagerfullname((String) map.get("managerfullname"));
        try {
            if (map.get("createtime") != null) {
                manager.setCreatetime(sdf.parse((String) map.get("createtime")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return manager;
    }
} 